package hz.mobileproject.pda.firesafety.activity;

import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.zxing.activity.CaptureActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import cn.droidlover.xdroidmvp.mvp.XActivity;
import hz.mobileproject.pda.R;
import hz.mobileproject.pda.broadcast.HandleBroadcast;
import hz.mobileproject.pda.broadcast.IShowBarcodeStr;
import hz.mobileproject.pda.entity.request.Request_fire_end;
import hz.mobileproject.pda.entity.request.Request_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.Response_loadPoliceInfo;
import hz.mobileproject.pda.firesafety.adapter.FireSafetyAdapter;
import hz.mobileproject.pda.firesafety.bean.FireSafetyThingBean;
import hz.mobileproject.pda.firesafety.bean.Request_queryFireFighting;
import hz.mobileproject.pda.firesafety.bean.Request_start_fire;
import hz.mobileproject.pda.firesafety.presenter.PStartFireQingDian;
import hz.mobileproject.pda.firesafety.view.FireSafetyUpdatePopWindow;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.ui.view.LoadingDialog;
import hz.mobileproject.pda.utils.CommonUtil;

/**
 * Created by hasee on 2017/11/16.
 * 消防器材检查
 */
public class FireSafetyActivity extends XActivity<PStartFireQingDian> implements IShowBarcodeStr{
    //打开扫描界面请求码
    private int REQUEST_CODE = 0x01;
    //扫描成功返回码
    private int RESULT_OK = 0xA1;

    private ListView mListView;
    private FireSafetyAdapter mAdapter;
    private List<FireSafetyThingBean> mList = new ArrayList<>();
    private LoadingDialog mUpDialog;
    private HandleBroadcast mHandleBroadcast;
    private SoundPool mSoundPool;
    private int mSoundId;
    private Button mbtZxingCode;
    private Button mbtEnd;
    private LinearLayout mLLRoot;
    private TextView mTvNum;
    private boolean mbIsFirstPolice = true;
    private String mstrDepartmentId;
    private String mstrCusNumber;
    private String mstrPoliceId;
    private String mstrCheckId;
    private int mintCurrNum;
    private int mintAllNum;
    private Gson mGson = new Gson();

    private class PopWindowCallBack implements FireSafetyUpdatePopWindow.FireSafetyCallback {
        @Override
        public void onSave(String assetCode, String condition) {
            calling(assetCode, condition);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) { //RESULT_OK = -1
            Bundle bundle = data.getExtras();
            String msg = bundle.getString("qr_scan_result");
            chooseAndShowPopWindow(msg);
        }
    }

    @Override
    public void onBackPressed() {
        ToastUtils.showLong("请点击<清点结束>按钮");
    }

    @Override
    public void onWidgetClick(View view) {
        switch (view.getId()){
            case R.id.bt_zxing_code_fire:
                if(CommonUtil.isCameraCanUse()){
                    Intent intent = new Intent(FireSafetyActivity.this, CaptureActivity.class);
                    startActivityForResult(intent, REQUEST_CODE);
                }else{
                    Toast.makeText(this,"请打开此应用的摄像头权限！",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.bt_fire_end:
                Request_fire_end request_fire_end = new Request_fire_end(
                        mstrCusNumber,mstrCheckId,TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
                getP().setData(mGson.toJson(request_fire_end), PStartFireQingDian.S_INT_TYPE_FIRE_SAFETY_END);
                break;
            default:
                break;
        }
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        initView();
        if (Constance.isNeiMeng){
            mbtZxingCode.setVisibility(View.VISIBLE);
            mUpDialog.setMessage("正在加载消防器材列表。。。").show();
            loadPoliceInfoByNet(getIntent().getStringExtra("police_tiaoma").substring(1));
        }else {
            mbtZxingCode.setVisibility(View.GONE);
            initScan();
            mUpDialog.setMessage("请扫描民警条形码").show();
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_fire_safety;
    }

    @Override
    public PStartFireQingDian newP() {
        return new PStartFireQingDian();
    }

    private void initView() {
        mLLRoot = (LinearLayout) findViewById(R.id.fire_safety_root);
        mTvNum = (TextView) findViewById(R.id.tv_num_fire_safety);
        mListView = (ListView) findViewById(R.id.lv_fire_safety);
        mbtZxingCode = (Button) findViewById(R.id.bt_zxing_code_fire);
        mbtEnd = (Button) findViewById(R.id.bt_fire_end);
        mUpDialog = new LoadingDialog(this);
        mAdapter = new FireSafetyAdapter(this, mList);
        mListView.setAdapter(mAdapter);
        mbtEnd.setOnClickListener(this);
        mbtZxingCode.setOnClickListener(this);
    }

    /**
     * 初始化条形码扫描
     */
    private void initScan() {
        mHandleBroadcast = new HandleBroadcast(this, this);
        mSoundPool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
        mSoundId = mSoundPool.load("/etc/Scan_new.ogg", 1);
    }

    /**
     * 扫码返回
     * @param msg
     */
    @Override
    public void updateText(String msg) {
        mSoundPool.play(mSoundId, 1, 1, 0, 0, 1);
        if (mbIsFirstPolice){
//            if (msg.contains("P")){
                mbIsFirstPolice = false;
                mUpDialog.setMessage("正在加载消防器材列表。。。");
                loadPoliceInfoByNet(msg.contains("P") ? msg.substring(1): msg);
//            }else {
//                ToastUtils.showLong("扫描的不是警员条码");
//            }
            return;
        }

        chooseAndShowPopWindow(msg);
    }

    private void chooseAndShowPopWindow(String msg){
        boolean haveFlag = false;
        for (FireSafetyThingBean thingBean : mList){
            if (thingBean.getAssetCode().equals(msg)){
                haveFlag = true;
                //显示PopupWindow
                FireSafetyUpdatePopWindow popWindow = new FireSafetyUpdatePopWindow(
                        FireSafetyActivity.this, thingBean, new PopWindowCallBack());
                popWindow.showPopupwindow(mLLRoot);
                break;
            }
        }
        if (!haveFlag){
            ToastUtils.showLong("列表中不存在该消防器材");
        }
    }

    /**
     * 请求警员信息
     * @param policeId
     */
    private void loadPoliceInfoByNet(String policeId){
        Request_loadPoliceInfo callroll_loadPoliceInfo = new Request_loadPoliceInfo();
        callroll_loadPoliceInfo.setCusNumber(SPUtils.getInstance("app_login").getString("cusnumber"));
        callroll_loadPoliceInfo.setPoliceCode(policeId);
        getP().setData(mGson.toJson(callroll_loadPoliceInfo), PStartFireQingDian.S_INT_TYPE_LOAD_POLICE_INFO);
    }

    /**
     * 清点
     * @param assetCode
     * @param condition
     */
    private void calling(String assetCode, String condition){
        try {
            JSONObject js = new JSONObject();
            js.put("cus_number", mstrCusNumber);
            js.put("check_id", mstrCheckId);
            js.put("police_id", mstrPoliceId);
            js.put("asset_code",assetCode);
            js.put("condition",condition);
            js.put("time",TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
            String jsonObjectInfo = js.toString();
            getP().startCalling(jsonObjectInfo, null);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 网络请求成功
     * @param dataJson
     * @param type
     */
    public void onNetWorkSuccess(String dataJson, int type) {
        switch (type){
            case PStartFireQingDian.S_INT_TYPE_LOAD_POLICE_INFO:
                Response_loadPoliceInfo loadPoliceInfo = mGson.fromJson(dataJson, Response_loadPoliceInfo.class);
                mstrDepartmentId = loadPoliceInfo.getDepartment_id() + "";
                String departmentName = loadPoliceInfo.getDepartment_name();
                mstrPoliceId = loadPoliceInfo.getPolice_id();
                String policeName = loadPoliceInfo.getPolice_name();
                String nowTime = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
                mstrCusNumber = loadPoliceInfo.getCus_number() + "";
                //开始
                Request_start_fire request_start_fire = new Request_start_fire(
                        mstrCusNumber,mstrDepartmentId,departmentName,mstrPoliceId,policeName, nowTime);
                getP().setData(mGson.toJson(request_start_fire), PStartFireQingDian.S_INT_TYPE_FIRE_SAFETY_START);
                break;
            case PStartFireQingDian.S_INT_TYPE_FIRE_SAFETY_START:
                try {
                    JSONObject jsonObject = new JSONObject(dataJson);
                    mstrCheckId = jsonObject.getString("check_id");
//                    String preCount = jsonObject.getString("pre_count");
                    //加载列表
                    Request_queryFireFighting query = new Request_queryFireFighting(mstrCusNumber,mstrDepartmentId,mstrCheckId);
                    getP().setData(mGson.toJson(query), PStartFireQingDian.S_INT_TYPE_FIRE_SAFETY_LOAD_LIST);
                } catch (JSONException e) {
                    e.printStackTrace();
                    ToastUtils.showLong("开始信息解析失败");
                    FireSafetyActivity.this.finish();
                }
                break;
            case PStartFireQingDian.S_INT_TYPE_FIRE_SAFETY_LOAD_LIST:
                try {
                    JSONArray jsonArray = new JSONArray(dataJson);
                    if (jsonArray.length()>0){
                        for (int i=0;i<jsonArray.length();i++){
                            FireSafetyThingBean bean = new FireSafetyThingBean();
                            JSONObject item = jsonArray.getJSONObject(i);
                            bean.setBoxName(item.getString("box_name"));
                            bean.setAssetCode(item.getString("asset_code"));
                            bean.setCode(item.getString("code"));
                            bean.setName(item.getString("name"));
                            bean.setNameId(item.getString("name_id"));
                            bean.setPurchaseDate(item.getString("purchase_date"));
                            bean.setProduceDate(item.getString("produce_date"));
                            bean.setExpiredDate(item.getString("expired_date"));
                            bean.setChangeDate(item.getString("change_date"));
                            bean.setImageUrl(item.getString("image_url"));
                            bean.setDeptId(item.getString("dept_id"));
                            bean.setDeptName(item.getString("dept_name"));
                            mList.add(bean);
                        }
                        mUpDialog.dismiss();
                        mintAllNum = jsonArray.length();
                        mTvNum.setText(mintCurrNum + "/" +mintAllNum);
                        mAdapter.notifyDataSetChanged();
                    }else {
                        ToastUtils.showLong("列表无数据");
                        FireSafetyActivity.this.finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    ToastUtils.showLong("列表信息解析失败");
                    FireSafetyActivity.this.finish();
                }
                break;
            case PStartFireQingDian.S_INT_TYPE_FIRE_SAFETY_CALLING:
                try {
                    JSONObject jsonObject = new JSONObject(dataJson);
                    String asseCode = jsonObject.getString("asset_code");
                    for (int i=mList.size()-1;i>=0;i--){
                        if (mList.get(i).getAssetCode().equals(asseCode)){
                            ToastUtils.showShort("保存成功");
                            mList.remove(i);
                            mintCurrNum++;
                            mTvNum.setText(mintCurrNum + "/" +mintAllNum);
                            break;
                        }
                    }
                    mAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case PStartFireQingDian.S_INT_TYPE_FIRE_SAFETY_END:
                ToastUtils.showLong("结束成功");
                FireSafetyActivity.this.finish();
                break;
            default:
                break;
        }
    }

    /**
     * 网络请求失败
     * @param dataJson
     * @param type
     */
    public void onNetWorkError(String dataJson, int type) {
        switch (type){
            case PStartFireQingDian.S_INT_TYPE_LOAD_POLICE_INFO:
                ToastUtils.showLong("获取民警信息失败，错误信息:" + dataJson);
                FireSafetyActivity.this.finish();
                break;
            case PStartFireQingDian.S_INT_TYPE_FIRE_SAFETY_START:
                ToastUtils.showLong("开启消防检查失败，错误信息:" + dataJson);
                FireSafetyActivity.this.finish();
                break;
            case PStartFireQingDian.S_INT_TYPE_FIRE_SAFETY_LOAD_LIST:
                ToastUtils.showLong("加载消防器材列表失败，错误信息:" + dataJson);
                FireSafetyActivity.this.finish();
                break;
            case PStartFireQingDian.S_INT_TYPE_FIRE_SAFETY_CALLING:
                ToastUtils.showLong("清点消防器材失败，错误信息:" + dataJson);
                break;
            case PStartFireQingDian.S_INT_TYPE_FIRE_SAFETY_END:
                ToastUtils.showLong("结束消防器材异常，异常信息:" + dataJson);
                FireSafetyActivity.this.finish();
                break;
            default:
                break;
        }
    }

}

